package com.uddenberg.wt;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import com.uddenberg.wt.dbdefinitions.DailyDataDefinition.DailyDataColumns;
import com.uddenberg.wt.dbdefinitions.FoodMealDataDefinition.FoodMealDataColumns;
import com.uddenberg.wt.dbdefinitions.FoodOtherDataDefinition.FoodOtherDataColumns;
import com.uddenberg.wt.dbdefinitions.GeneralDataDefinition.GeneralDataColumns;

import android.app.ActivityGroup;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.telephony.TelephonyManager;
import android.text.util.Linkify;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class StatisticsActivity extends ActivityGroup {

	private Button btnUpload;
	
	final Handler mDebugHandler = new Handler();
	private boolean mUploadSuccess = false;
	private String mUploadUrl;
	private TextView uploadUrl;
	private Cursor cursor;
	private Intent intent;
	private SharedPreferences appSettings;
	
	
	private static final String[] GENERAL_PROJECTION = new String[] {
        GeneralDataColumns._ID, // 0
        GeneralDataColumns.TIME, // 1
        GeneralDataColumns.WELLNESS, // 2
        GeneralDataColumns.STRESS, // 3
        GeneralDataColumns.ENERGY, // 4
        GeneralDataColumns.HAPPINESS, // 5
        GeneralDataColumns.ACTIVITY, // 6
        GeneralDataColumns.FOCUS, // 7
        GeneralDataColumns.VALUE, // 8
    };
	private static final String[] DAILY_PROJECTION = new String[] {
        DailyDataColumns._ID, // 0
        DailyDataColumns.DATE, // 1
        DailyDataColumns.SLEEP_START, // 2
        DailyDataColumns.SLEEP_END, // 3
        DailyDataColumns.QUALITY, // 4
        DailyDataColumns.EXERCISE_START, // 5
        DailyDataColumns.EXERCISE_END, // 6
        DailyDataColumns.INTENSITY, // 7
        DailyDataColumns.SICK, // 8
    };
	private static final String[] FOOD_MEAL_PROJECTION = new String[] {
        FoodMealDataColumns._ID, // 0
        FoodMealDataColumns.DATE, // 1
        FoodMealDataColumns.FULL, // 2
        FoodMealDataColumns.HEALTHY, // 3
        FoodMealDataColumns.CAFFEINE, // 4
    };
	private static final String[] FOOD_OTHER_PROJECTION = new String[] {
		FoodOtherDataColumns._ID, // 0
		FoodOtherDataColumns.DATE, // 1
		FoodOtherDataColumns.CAFFEINE, // 2
		FoodOtherDataColumns.SNACK, // 3
		FoodOtherDataColumns.HEALTHY, // 4
    };
	
	/*
	@Override
	public void onSaveInstanceState(Bundle savedInstanceState) {
	  // Save UI state changes to the savedInstanceState.
	  // This bundle will be passed to onCreate if the process is
	  // killed and restarted.
	  savedInstanceState.putString("mUploadUrl", mUploadUrl);
	  // etc.
	  super.onSaveInstanceState(savedInstanceState);
	}
	
	@Override
	public void onRestoreInstanceState(Bundle savedInstanceState) {
	  super.onRestoreInstanceState(savedInstanceState);
	  // Restore UI state from the savedInstanceState.
	  // This bundle has also been passed to onCreate.
	  String mUploadUrl = savedInstanceState.getString("mUploadUrl");
	  uploadUrl = (TextView)findViewById(R.id.statistics_upload_url);
      uploadUrl.setText(mUploadUrl);
	}
	*/
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.layout.menu, menu);
	    return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	        case R.id.icontext: Toast.makeText(this, "You pressed the icon and text!", Toast.LENGTH_LONG).show();
	                            break;
	    }
	    return true;
	}
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.statistics);
        
        
        appSettings = getSharedPreferences("AppPreferences", MODE_PRIVATE);  
        mUploadUrl = appSettings.getString("lastUploadUrl", "N/A");
        
        intent = getIntent();
        
        btnUpload = (Button)findViewById(R.id.statistics_btn_upload);
        btnUpload.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				doUpload();
			}
		});
        
        uploadUrl = (TextView)findViewById(R.id.statistics_upload_url);
        uploadUrl.setText(mUploadUrl);
    }
    
    final Runnable mFinishUpload = new Runnable() {
    	public void run() {
    		alertUploadStatus();
    	}
	};
    
	private void alertUploadStatus() {
		if (mUploadSuccess) {
			Toast.makeText(getApplicationContext(), "File upload successful, see the Statistics tab for more information", Toast.LENGTH_LONG).show();
			uploadUrl.setText(mUploadUrl);
			uploadUrl.setAutoLinkMask(Linkify.WEB_URLS);
			SharedPreferences.Editor prefEditor = appSettings.edit();  
			prefEditor.putString("lastUploadUrl", mUploadUrl);  
			prefEditor.commit();  
		} else {
			Toast.makeText(getApplicationContext(), "File upload failed", Toast.LENGTH_LONG).show();
		}
	}
    
    private void doUpload() {
		
		Toast.makeText(getApplicationContext(), "File upload begun", Toast.LENGTH_LONG).show();
		Thread t = new Thread() {
			@Override
			public void run() {
				
				boolean mSuccessFileCreation = true;
				TelephonyManager mTelephonyMgr = 
		            (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
		    	String imei = mTelephonyMgr.getDeviceId();
		    	
		    	File root = Environment.getExternalStorageDirectory();
		    	// Create GENERAL csv
		        final File general_file = new File(root, imei+"_general.csv");
		        intent.setData(GeneralDataColumns.CONTENT_URI);
				cursor = managedQuery(getIntent().getData(), GENERAL_PROJECTION, null, null,
		                GeneralDataColumns.DEFAULT_SORT_ORDER);
		        try {
					FileWriter writer = new FileWriter(general_file);
					cursor.moveToFirst();
					while (cursor.isAfterLast() == false) {
						writer.append(Integer.toString(cursor.getInt(1)));
						writer.append(';');
						writer.append(Integer.toString(cursor.getInt(2)));
						writer.append(';');
						writer.append(Integer.toString(cursor.getInt(3)));
						writer.append(';');
						writer.append(Integer.toString(cursor.getInt(4)));
						writer.append(';');
						writer.append(Integer.toString(cursor.getInt(5)));
						writer.append(';');
						writer.append(Integer.toString(cursor.getInt(6)));
						writer.append(';');
						writer.append(Integer.toString(cursor.getInt(7)));
						writer.append(';');
						writer.append(Integer.toString(cursor.getInt(8)));
						writer.append('\n');
						cursor.moveToNext();
						
					}
					writer.flush();
					writer.close();

				} catch (IOException e) {
					mSuccessFileCreation = false;
					Log.e("Generate General", "Failed: " + e.getMessage() + " Stacktrace: " + e.getStackTrace());
				}
				
				
				// Create DAILY csv
				final File daily_file = new File(root, imei+"_daily.csv");
		        intent.setData(DailyDataColumns.CONTENT_URI);
				cursor = managedQuery(getIntent().getData(), DAILY_PROJECTION, null, null,
						DailyDataColumns.DEFAULT_SORT_ORDER);
		        try {
					FileWriter writer = new FileWriter(daily_file);
					cursor.moveToFirst();
					while (cursor.isAfterLast() == false) {
						writer.append(Integer.toString(cursor.getInt(1)));
						writer.append(';');
						writer.append(Integer.toString(cursor.getInt(2)));
						writer.append(';');
						writer.append(Integer.toString(cursor.getInt(3)));
						writer.append(';');
						writer.append(Integer.toString(cursor.getInt(4)));
						writer.append(';');
						writer.append(Integer.toString(cursor.getInt(5)));
						writer.append(';');
						writer.append(Integer.toString(cursor.getInt(6)));
						writer.append(';');
						writer.append(Integer.toString(cursor.getInt(7)));
						writer.append(';');
						writer.append(Integer.toString(cursor.getInt(8)));
						writer.append('\n');
						cursor.moveToNext();
						
					}
					writer.flush();
					writer.close();
				} catch (IOException e) {
					mSuccessFileCreation = false;
					Log.e("Generate Daily", "Failed: " + e.getMessage() + " Stacktrace: " + e.getStackTrace());
				}
				
				// Create FOOD_MEAL csv
				final File food_meal_file = new File(root, imei+"_food_meal.csv");
		        intent.setData(FoodMealDataColumns.CONTENT_URI);
				cursor = managedQuery(getIntent().getData(), FOOD_MEAL_PROJECTION, null, null,
						FoodMealDataColumns.DEFAULT_SORT_ORDER);
		        try {
					FileWriter writer = new FileWriter(food_meal_file);
					cursor.moveToFirst();
					while (cursor.isAfterLast() == false) {
						writer.append(Integer.toString(cursor.getInt(1)));
						writer.append(';');
						writer.append(Integer.toString(cursor.getInt(2)));
						writer.append(';');
						writer.append(Integer.toString(cursor.getInt(3)));
						writer.append(';');
						writer.append(Integer.toString(cursor.getInt(4)));
						writer.append('\n');
						cursor.moveToNext();
						
					}
					writer.flush();
					writer.close();
				} catch (IOException e) {
					mSuccessFileCreation = false;
					Log.e("Generate Food meal", "Failed: " + e.getMessage() + " Stacktrace: " + e.getStackTrace());
				}
				
				// Create FOOD_OTHER csv
				final File food_other_file = new File(root, imei+"_food_other.csv");
		        intent.setData(FoodOtherDataColumns.CONTENT_URI);
				cursor = managedQuery(getIntent().getData(), FOOD_OTHER_PROJECTION, null, null,
						FoodOtherDataColumns.DEFAULT_SORT_ORDER);
		        try {
					FileWriter writer = new FileWriter(food_other_file);
					cursor.moveToFirst();
					while (cursor.isAfterLast() == false) {
						writer.append(Integer.toString(cursor.getInt(1)));
						writer.append(';');
						writer.append(Integer.toString(cursor.getInt(2)));
						writer.append(';');
						writer.append(Integer.toString(cursor.getInt(3)));
						writer.append(';');
						writer.append(Integer.toString(cursor.getInt(4)));
						writer.append(';');
						writer.append(Integer.toString(cursor.getInt(5)));
						writer.append('\n');
						cursor.moveToNext();
						
					}
					writer.flush();
					writer.close();
				} catch (IOException e) {
					mSuccessFileCreation = false;
					Log.e("Generate food other", "Failed: " + e.getMessage() + " Stacktrace: " + e.getStackTrace());
				}
				
				
				if(mSuccessFileCreation == true) {
					// No error with generating files
					try {
						JSONObject json_general = postFile(general_file, "general", "");
						String identifier = json_general.getString("identifier");
						if(identifier.length() > 0) {
							JSONObject json_daily = postFile(daily_file, "daily", identifier);
							JSONObject json_food_meal = postFile(food_meal_file, "food_meal", identifier);
							JSONObject json_food_other = postFile(food_other_file, "food_other", identifier);
							
						
							try {
								if(
										json_general.getString("status").equals("ok") &&
										json_daily.getString("status").equals("ok") &&
										json_food_meal.getString("status").equals("ok") &&
										json_food_other.getString("status").equals("ok")
									) {
									
									mUploadUrl = json_general.getString("url");
									mUploadSuccess = true;
									
								} else {
									mUploadSuccess = false;
								}
							} catch (JSONException e) {
								mUploadSuccess = false;
							}
						} else {
							mUploadSuccess = false;
						}
					} catch (Exception e1) {
						mUploadSuccess = false;
					}
				} else {
					mUploadSuccess = false;
				}
				mDebugHandler.post(mFinishUpload);
			}
		};
		t.start();
    }
    
    
    
    private JSONObject postFile(File file, String type, String identifier) throws Exception {
    	JSONObject json = new JSONObject();
    	try {
			DefaultHttpClient httpclient = new DefaultHttpClient();
 
			HttpPost httpost = new HttpPost("http://dev.a3j.se/~anud/wellnesstracker/recieve.php");
			MultipartEntity entity = new MultipartEntity();
			entity.addPart("type", new StringBody(type));
			entity.addPart("identifier", new StringBody(identifier));
			entity.addPart("file", new FileBody(file));
			httpost.setEntity(entity);
			
			httpclient.getParams().setBooleanParameter("http.protocol.expect-continue", false);
			
			//httpost.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);  
 
			HttpResponse response;
							
			response = httpclient.execute(httpost);
			//Log.e("httpPost", "Result: " + response.getStatusLine());

			if (entity != null) {
				entity.consumeContent();
			}
			
			
			

	        try {
	            HttpEntity entity2 = response.getEntity();

	            if (entity2 != null) {

	                // A Simple JSON Response Read
	                InputStream instream = entity2.getContent();
	                String result= convertStreamToString(instream);

	                json = new JSONObject(result);

	                instream.close();
	            }

	        } catch (ClientProtocolException e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	        } catch (IOException e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	        } catch (JSONException e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	        }

			Log.e("json:",json.toString());
			
		} catch (IOException ioex) {
			Log.e("Upload", "Upload failed IOException: " + ioex.getMessage() + " Stacktrace: " + ioex.getStackTrace());
			mUploadSuccess = false;
		} catch (Exception ex) {
			Log.e("Upload", "Upload failed: " + ex.getMessage() + " Stacktrace: " + ex.getStackTrace());
			mUploadSuccess = false;

		}
		return json;
    }
    
    
    public static String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
}
